package com.ljd.server.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * Swagger配置类
 *
 * @author ljd on 2022/1/22
 * @PACKAGE_NAME: com.ljd.server.config
 * @PROJECT_NAME: yeb
 */
@Configuration
@EnableSwagger2         // 开启swagger2
public class Swagger2Config {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())      //设置具体的摘要信息
                .select()
                // 设置将指定包下的单元方法进行扫描写入API文档中
                .apis(RequestHandlerSelectors.basePackage("com.ljd.server.controller"))
                // 任何路径都要进行记录
                .paths(PathSelectors.any())
                .build()
                // 用于授权
                .securityContexts(securityContexts())
                .securitySchemes(securitySchemes());
    }

    private List<ApiKey> securitySchemes() {
        // 设置请求信息
        List<ApiKey> result = new ArrayList<>();
        // 当前请求头的参数的名称为Authorization,keyname也为Authorization,设置在请求头中
        ApiKey apiKey = new ApiKey("Authorization", "Authorization", "Header");
        result.add(apiKey);
        return result;
    }


    private List<SecurityContext> securityContexts() {
        // 设置需要登录认证的路径
        List<SecurityContext> result = new ArrayList<>();
        result.add(getContextByPath("/hello/.*"));
        return result;
    }

    private SecurityContext getContextByPath(String s) {
        return SecurityContext.builder()
                .securityReferences(defaultAuth())
                .forPaths(PathSelectors.regex(s))
                .build();
    }

    private List<SecurityReference> defaultAuth() {
        List<SecurityReference> result = new ArrayList<>();
        // 作用于全局
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0]= authorizationScope;
        result.add(new SecurityReference("Authorization",authorizationScopes));
        return result;
    }


    public ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .contact(new Contact("ljd","http://localhost:8081/doc.html","xxxxx@qq.com"))
                .title("云E办接口文档")
                .description("文档的描述")
                .version("1.0.0")
                .build();
    }
}
